package com.ligq.h265toupinpush.call

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface

class ReceiveH264Player(private val width: Int, private val height: Int) {

    private lateinit var mediaCodec: MediaCodec
    fun initMediaCodec(surface: Surface) {
        Log.d(TAG, "initMediaCodec: width=$width,height=$height")
        try {
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
            val format =
                MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height)
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 30)
            format.setInteger(MediaFormat.KEY_BIT_RATE, width * height)
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10)
            mediaCodec.configure(format, surface, null, 0)
            mediaCodec.start()
        } catch (e: Exception) {
            Log.e(TAG, "initMediaCodec: ", e)
        }
    }

    fun decode(data: ByteArray) {
        val bufferInfo = MediaCodec.BufferInfo()
        val inputIndex = mediaCodec.dequeueInputBuffer(10000)
        if (inputIndex >= 0) {
            val inputBuffer = mediaCodec.getInputBuffer(inputIndex)
            inputBuffer?.run {
                clear()
                if(data[0].toInt()!=0) {
                    put(data, 1, data.size - 1)
                }else{
                    put(data, 0, data.size)
                }
            }
            mediaCodec.queueInputBuffer(inputIndex, 0, data.size, System.currentTimeMillis(), 0)
        }

        var outIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000)
        while (outIndex >= 0) {
            mediaCodec.releaseOutputBuffer(outIndex, true)
            outIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000)
        }

    }
}